package cn.firstsoft.firstframe.plugins.kingdee.k3.web;

import cn.firstsoft.firstframe.plugins.kingdee.cloud.CloudUtils;
import cn.firstsoft.firstframe.plugins.kingdee.plm.util.PlmSSOUtils;
import cn.firstsoft.firstframe.util.KbiSSOUtil;
import cn.firstsoft.modules.integration.domain.IntegratSysBaseInfo;
import cn.firstsoft.modules.integration.domain.IntegratSysConf;
import cn.firstsoft.modules.integration.service.logic.IntegratSysConfManager;
import cn.firstsoft.modules.weibo.service.logic.WeiboManager;
import java.io.File;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.springframework.web.servlet.ModelAndView;
import org.springside.core.Constants;
import org.springside.core.commons.BaseManageController;
import org.springside.modules.security.domain.User;
import org.springside.modules.security.domain.UserSession;
import org.springside.modules.security.service.logic.UserManager;

public class K3ERPLoginManagerController
  extends BaseManageController
{
  private UserManager userManager;
  private WeiboManager weiboManager;
  private IntegratSysConfManager integratSysConfManager;
  
  public ModelAndView onK3ERPLogin(HttpServletRequest request, HttpServletResponse response)
    throws Exception
  {
    UserSession user = (UserSession)request.getSession().getAttribute("loginUser");
    String loginId = URLEncoder.encode(user.getLoginid(), "UTF-8");
    StringBuffer k3Url = new StringBuffer();
    
    String sysConfId = request.getParameter("sysConfId");
    String defaultSob = request.getParameter("defaultSob");
    try
    {
      IntegratSysConf isc = null;
      if ((sysConfId != null) && (!"".equals(sysConfId))) {
        isc = this.integratSysConfManager.get(new Integer(sysConfId));
      }
      String sysCode = isc.getIntegratSysBaseInfo().getSysCode();
      if (sysCode.equals("K/3PLM"))
      {
        k3Url.append(isc.getSysServer().trim()).append("/").append(Constants.K3PLM_LOGIN_URL);
        if (k3Url.indexOf("?") == -1) {
          k3Url.append("?");
        } else {
          k3Url.append("&");
        }
        String validCode = PlmSSOUtils.validCode(isc.getSysServer().trim() + "/" + Constants.K3PLM_WEBSERVICE_URL, 
          user.getLoginid());
        k3Url.append("UserCode=").append(user.getLoginid()).append("&ValidCode=").append(validCode);
      }
      else if (!sysCode.equals("K/3BI"))
      {
        if (sysCode.equals("KBI"))
        {
          k3Url.append(isc.getSysServer().trim()).append(File.separator).append("index.jsp?").append(KbiSSOUtil.getBISSOUrl(user));
        }
        else if (sysCode.equals("KDWB"))
        {
          try
          {
            User u = this.userManager.getUser(user.getId());
            String token = u.getOauthToken();
            if ((token == null) || (token.trim().equals("")))
            {
              response.setCharacterEncoding("UTF-8");
              response.setContentType("text/plain;charset=UTF-8");
              StringBuffer temp = new StringBuffer("<script type='text/javascript'>alert('未绑定云之家!');");
              temp.append("window.opener.location.href=('../../modules/setting/user.do?method=modifyInfo');");
              
              temp.append("window.close();");
              temp.append("</script>");
              response.getWriter().append(temp);
              return null;
            }
            String url = this.weiboManager.singleLogin(this.userManager.getUser(user.getId()), null);
            k3Url.append(url);
          }
          catch (Exception e)
          {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/plain;charset=UTF-8");
            response.getWriter().append("连接异常，请联系管理员!");
            return null;
          }
        }
        else if (sysCode.equals("s-HR"))
        {
          k3Url.append("../../shr/loginhr.jsp");
        }
        else if (sysCode.equals("K/3Cloud"))
        {
          User u = this.userManager.getUser(user.getId());
          k3Url.append(CloudUtils.getSSOURL(u.getName()));
        }
        else
        {
          k3Url.append(isc.getSysServer().trim()).append("/").append(getK3sub(sysCode)).append(Constants.K3HR_SSO_URL).append("&AcctID=").append(defaultSob).append("&UserName=").append(loginId);
        }
      }
      this.logger.info(k3Url.toString());
      System.out.println(k3Url.toString());
      response.sendRedirect(k3Url.toString());
    }
    catch (Exception e)
    {
      this.logger.error("K3ERPLoginManagerController onK3ERPLogin failed!", e);
      response.setCharacterEncoding("UTF-8");
      response.setContentType("text/plain;charset=UTF-8");
      
      response.getWriter().append("出错了！单点登录不成功，请检查集成系统配置是否正确。");
      return null;
    }
    return null;
  }
  
  private static String getK3sub(String sysCode)
  {
    String k3sub = "";
    if (sysCode.equals("K/3HR")) {
      k3sub = Constants.K3HR_SERVER_NAME;
    } else if (sysCode.equals("K/3WEB")) {
      k3sub = Constants.K3WEB_SERVER_NAME;
    } else if (sysCode.equals("K/3SRM")) {
      k3sub = Constants.K3SRM_SERVER_NAME;
    }
    return k3sub;
  }
  
  private boolean isUrl(String strURL)
    throws Exception
  {
    URL url = new URL(strURL);
    URLConnection connection = url.openConnection();
    HttpURLConnection httpConn = (HttpURLConnection)connection;
    int code = httpConn.getResponseCode();
    if (code == 200) {
      return true;
    }
    return false;
  }
  
  public void setIntegratSysConfManager(IntegratSysConfManager integratSysConfManager)
  {
    this.integratSysConfManager = integratSysConfManager;
  }
  
  public WeiboManager getWeiboManager()
  {
    return this.weiboManager;
  }
  
  public void setWeiboManager(WeiboManager weiboManager)
  {
    this.weiboManager = weiboManager;
  }
  
  public UserManager getUserManager()
  {
    return this.userManager;
  }
  
  public void setUserManager(UserManager userManager)
  {
    this.userManager = userManager;
  }
}
